﻿/**********************************************
 * 功能名称：老客户挽回问卷
 *
 * 列表显示客户信息。约束条件为店铺、客户等级。不包括订制客户、新客户。
 * 
 **************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CSM.Controllers;
using CSM.Models;
using System.Text;

namespace CSM.Views.Kefu
{
    public partial class MissingCustomerDoWJ : System.Web.UI.Page
    {
        CustomDataContext db = new CustomDataContext();
        public string alert;
        static DateTime begintime = Convert.ToDateTime("2000-1-1 0:0:0");
        static DateTime endtime = Convert.ToDateTime("2100-1-1 0:0:0");
        static Decimal MinMoney = 0;
        static Decimal MaxMoney = 0;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {


                var allProvince = from a in db.TCrm_Sys_Items where a.ClassID == "sf" select a;
                DropDownList_Provinces.Items.Add(new ListItem("--省份--", ""));
                foreach (var query in allProvince)
                {
                    DropDownList_Provinces.Items.Add(new ListItem(query.ItemName.Trim(), query.ItemName.Trim()));

                }
                //查询当前操作员的店铺权限及客户回访等级权限。
                string MyUserId = HttpContext.Current.Session[SystemVars.sysSessionUserId].ToString();
                var RightList = from a in db.TCsm_JS_User
                                where a.UserID == MyUserId
                                select new
                                {
                                    a.ShopRightID,
                                    a.KefuRightID

                                };
                if (RightList.Count() > 0)
                {

                    string MyShopRightIdList = RightList.Single().ShopRightID;
                    if (!string.IsNullOrEmpty(MyShopRightIdList))
                    {
                        var DropList_ShopRight = MyShopRightIdList.Split(',');
                        foreach (var MyItems in DropList_ShopRight)
                        {
                            var MyShopName = from a in db.TCrm_JC_Parameter
                                             where a.ID == Convert.ToInt32(MyItems)
                                             select a;
                            if (MyShopName.Count() == 1)
                            {
                                var AddItem = MyShopName.Single();
                                ListItem InsertItem = new ListItem(AddItem.ShopName, AddItem.ShopID);
                                //填充店铺列表
                                DropDownList_ShopId.Items.Add(InsertItem);
                            }

                        }
                    
                    }
                    string MyKefuRightIdList = RightList.Single().KefuRightID;
                    if (!string.IsNullOrEmpty(MyKefuRightIdList))
                    {
                        var DropList_KefuRight = MyKefuRightIdList.Split(',');
                        foreach (var MyItems in DropList_KefuRight)
                        {
                            var MyKefuRightName = (from a in db.TCrm_Sys_Items
                                                   where a.ItemID == MyItems
                                                   select a).Single();
                            if (MyKefuRightName.ItemID != "dzkh")
                            {
                                ListItem InsertItem = new ListItem(MyKefuRightName.ItemName, MyKefuRightName.ItemID);
                                //填充客户等级列表。
                                DropDownList_CustomerLevel.Items.Add(InsertItem);
                            }

                        }

                    }


                    //默认问卷信息保存到hiddenfield中。
                    var defaultStatId = (from a in db.TCrm_Sys_Items where a.ItemID == "whwj" select a.DefaultValue);
                    if (!string.IsNullOrEmpty(defaultStatId.Single()))
                    {
                        HiddenField_DefaultStat.Value = defaultStatId.Single().ToString();
                    }
                    else
                    {
                        Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "message", " <script>alert('客户问卷没有定义'); </script>");
                        return;
                    }


                    //BindMyData(0);
                    //int Totals = TotalPageAmount();
                    //int pages = (Totals % 10) == 0 ? (Totals / 10) : (Totals / 10 + 1);
                    //Label_Total.Text = "共" + pages.ToString();
                    //Label_CurrenPageAndTo.Text = "页，当前第1" + " 页，转到";
                }
            }
        }
        #region 绑定数据及翻页
        private void BindMyData(int PageIndex)
        {
            if (string.IsNullOrEmpty(TextBox_Min.Text) == false)
            {
                if (PublicMethod.IsNumeric(TextBox_Min.Text) == true)
                {
                    MinMoney = Convert.ToDecimal(TextBox_Min.Text);
                }
            }
            if (string.IsNullOrEmpty(TextBox_Max.Text) == false)
            {
                if (PublicMethod.IsNumeric(TextBox_Min.Text) == true)
                {
                    MaxMoney = Convert.ToDecimal(TextBox_Max.Text);
                }
            }
            string begin = TextBox_BeginTime.Text;
            string end = TextBox_EndTime.Text;
            string Outid = TextBox_Product.Text ;
            if (begin != "" || end != "")
            {
                try
                {
                    begintime = Convert.ToDateTime(begin);
                    endtime = Convert.ToDateTime(end);
                }
                catch
                {
                }
            }
            string KeySelect = DropDownList_Key.SelectedValue;
            string KeyWord = TextBox_Key.Text;
            string Provinces = DropDownList_Provinces.SelectedValue;
            var Customid = from c in db.VCrm_KF_Orders where (KeySelect == "Order" ? c.tid == KeyWord : false) select c;
            var querya = from c in db.TCrm_KF_Orders
                         where (Outid == "" ? false : c.outerid == Outid)
                         select c.buyer_nick;
            string BuyerNick = Customid.Count() == 1 ? Customid.Single().buyer_nick : "";
            string ShopId = DropDownList_ShopId.SelectedValue;
            string CustomerLevel = DropDownList_CustomerLevel.SelectedValue;
            string DefaultStatId = HiddenField_DefaultStat.Value;

            //获取当前用户等级的无订单时间。
            var NoOrderDay = from a in db.TCrm_Sys_Items
                             where a.ItemID == CustomerLevel
                             select a.DefaultValue;
            HiddenField_NoOrderDay.Value = NoOrderDay.Single();
            double Myday = 0-Convert.ToDouble(HiddenField_NoOrderDay.Value);

            int skipAccount = PageIndex * 10;
            
           
            string[] state = (from a in db.TCrm_WJ_CustomerAnswer where a.StatID == DefaultStatId select a.CustomerID).Distinct().ToArray();

             var MyQuery = (from a in db.TCrm_KF_Customer
                            where !state.Contains(a.CustomerID)
                            && a.BlackList==false
                            && a.NoCall == false
                            && a.CustomerLevel == CustomerLevel
                            && a.ShopID == ShopId
                             && (KeySelect == "" ? true : (KeySelect == "Ali" ? a.AliPayID.StartsWith(KeyWord) : (KeySelect == "Phone" ? a.MobliePhone.StartsWith(KeyWord) : (KeySelect == "Receiver" ? a.ReceiverName.StartsWith(KeyWord) : (KeySelect == "Order" ? (BuyerNick == "" ? true : a.TbID.StartsWith(BuyerNick)) : true)))))
                                //&& (Receive == "" ? true : a.ReceiverName.StartsWith(Receive))
                           && (MinMoney == Convert.ToDecimal(0) ? true : a.AllMoney > MinMoney)
                           && (MaxMoney == Convert.ToDecimal(0) ? true : a.AllMoney < MaxMoney)
                                //&& (Ali == "" ? true : a.AliPayID.StartsWith(Ali))
                                //&& (BuyerNick == "" ? true : a.TbID.StartsWith(BuyerNick))
                           && (Provinces == "" ? true : a.Province.StartsWith(Provinces))
                                //&& (Phone == "" ? true : a.MobliePhone.StartsWith(Phone))
                           && (begintime == Convert.ToDateTime("2000-1-1 0:0:0") ? true : a.FinalTime > begintime)
                           && (endtime == Convert.ToDateTime("2100-1-1 0:0:0") ? true : a.FinalTime < endtime)
                           && (querya.Count() == 0 ? true : querya.Contains(a.TbID))
                            && a.FinalTime < DateTime.Now.AddDays(Myday) 
                            select new 
                            { 
                              a.AllMoney,
                              a.CustomerID,
                              a.TbID,
                              a.CustomerName,
                              a.Province,
                              a.MobliePhone,
                              Address = (a.Address.Length >20 ? a.Address.Substring(0,20)+"...":a.Address),
                              a.AliPayID,
                              a.Email
                            
                            
                            
                            
                            }).Skip(skipAccount).Take(10);
            GridView_Orders.DataSource = MyQuery;
            GridView_Orders.DataBind();



            if (MyQuery.Count() > 0)
            {
                Panel_Browse.Visible = true;
            }
            else 
            {
                Panel_Browse.Visible = false;
                Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "message", " <script>alert('没有符合条件的记录'); </script>");
            }

        }

        //查询出当前记录信息的总条数。
        private int TotalPageAmount()
        {
            string begin = TextBox_BeginTime.Text;
            string end = TextBox_EndTime.Text;
            string KeySelect = DropDownList_Key.SelectedValue;
            string KeyWord = TextBox_Key.Text;
            string ShopId = DropDownList_ShopId.SelectedValue;
            string Outid =TextBox_Product.Text;
            var Customid = from c in db.VCrm_KF_Orders where (KeySelect == "Order" ? c.tid == KeyWord : true) select c;
            var querya = from c in db.TCrm_KF_Orders
                         where (Outid == "" ? true : c.outerid == Outid)
                         select c.buyer_nick;
            string Provinces = DropDownList_Provinces.SelectedValue;
            string BuyerNick = Customid.Count() == 1 ? Customid.Single().buyer_nick : "";
            int MyQuery = 0;
            string CustomerLevel = DropDownList_CustomerLevel.SelectedValue;
            string DefaultStatId = HiddenField_DefaultStat.Value;

            //获取当前用户等级的无订单时间。
            var NoOrderDay = from a in db.TCrm_Sys_Items
                             where a.ItemID == CustomerLevel
                             select a.DefaultValue;
            HiddenField_NoOrderDay.Value = NoOrderDay.Single();
            double Myday = 0 - Convert.ToDouble(HiddenField_NoOrderDay.Value);

         


            string[] state = (from a in db.TCrm_WJ_CustomerAnswer where a.StatID == DefaultStatId select a.CustomerID).Distinct().ToArray();
           MyQuery = (from a in db.TCrm_KF_Customer
                           where !state.Contains(a.CustomerID)
                           && a.BlackList==false
                           && a.NoCall == false   //标识为“免打扰的用户”不显示
                           && a.CustomerLevel == CustomerLevel
                           && a.ShopID == ShopId
                            && (KeySelect == "" ? true : (KeySelect == "Ali" ? a.AliPayID.StartsWith(KeyWord) : (KeySelect == "Phone" ? a.MobliePhone.StartsWith(KeyWord) : (KeySelect == "Receiver" ? a.ReceiverName.StartsWith(KeyWord) : (KeySelect == "Order" ? (BuyerNick == "" ? true : a.TbID.StartsWith(BuyerNick)): true)))))
                           && (MinMoney == Convert.ToDecimal(0) ? true : a.AllMoney > MinMoney)
                           && (MaxMoney == Convert.ToDecimal(0) ? true : a.AllMoney < MaxMoney)
                           && (Provinces == "" ? true : a.Province.StartsWith(Provinces))
                           && (begintime == Convert.ToDateTime("2000-1-1 0:0:0") ? true : a.FinalTime > begintime)
                           && (endtime == Convert.ToDateTime("2100-1-1 0:0:0") ? true : a.FinalTime < endtime)
                           && (querya.Count() == 0 ? true : querya.Contains(a.TbID))
                           && a.FinalTime < DateTime.Now.AddDays(Myday)   //客户的最后交易时间小于 回访标准天数值。
                           select a).Count(); 
            return MyQuery;
        }


        //点击按钮，执行查询
        protected void MyClick(object sender, EventArgs e)
        {
            int pageIndx = Convert.ToInt32(CurrentPage.Value);
            string starts = txtOrder.Text;
            int Totals = TotalPageAmount();
            int pages = (Totals % 10) == 0 ? (Totals / 10) : (Totals / 10 + 1);

            Label_Total.Text = "共" + pages.ToString();

            if (typeof(Button).IsInstanceOfType(sender))
            {
                string arg = ((Button)sender).CommandArgument.ToString().ToLower();

                switch (arg)
                {
                    case "first":

                        pageIndx = 0;

                        break;
                    case "gotopage":
                        if (TextBox_PageIndex.Text == "")
                        { pageIndx = 0; }
                        else
                        {
                            int xx = Convert.ToInt32(TextBox_PageIndex.Text);
                            if (xx > pages)
                            { pageIndx = pages - 1; }

                            else
                            { pageIndx = xx - 1; }


                        }
                        break;
                }

            }
            else if (typeof(LinkButton).IsInstanceOfType(sender))
            {

                string arg = ((LinkButton)sender).CommandArgument.ToString().ToLower();

                switch (arg)
                {
                    case "prev":
                        if (pageIndx > 0)
                        {
                            pageIndx = pageIndx - 1;
                        }
                        break;
                    case "next":
                        if (pageIndx < pages - 1)
                        {
                            pageIndx = pageIndx + 1;
                        }
                        break;
                    case "last":
                        pageIndx = pages - 1;
                        break;
                    case "first":
                        pageIndx = 0;
                        break;
                }

            }

            CurrentPage.Value = pageIndx.ToString();  //对保存页码状态信息的隐藏字段进行赋值。保存当前页码。
            Label_CurrenPageAndTo.Text = "页，当前第" + (pageIndx + 1).ToString() + " 页，转到";

            BindMyData(pageIndx);

        }

        #endregion
        protected void Button_CallBack_Command(object sender, CommandEventArgs e)
        {
            string myCustomerId  = e.CommandArgument.ToString().Trim();
            string DefaultStatId = HiddenField_DefaultStat.Value;
            var query = from a in db.TCrm_KF_Customer where a.CustomerID == myCustomerId select a;
            if (query.Single().IsLock == true)
            {
                alert = "<script>alert('该客户已被锁定，请回访下一个客户');</script>";
            }
            else
            {
            HttpContext.Current.Session[SystemVars.sysSessionCustomId] = myCustomerId;
            HttpContext.Current.Session[SystemVars.sysSessionWjType] = "whwj";
            query.Single().IsLock = true;
                db.SubmitChanges();
                Response.Redirect("../Wenjuan/html/" + DefaultStatId + ".html");
            }
            
        }
        protected void Button_Black_Command(object sender, CommandEventArgs e)
        {
            if (TextBox1.Value != "")
            {
                string IDList = TextBox1.Value.TrimEnd(new char[] { ',' });
                string[] CustomerId = IDList.Split(',');
                foreach (string id in CustomerId)
                {
                    var myEditQuery = (from a in db.TCrm_KF_Customer where a.CustomerID == id select a).Single();
                    myEditQuery.BlackList = true; ;
                    db.SubmitChanges();
                }
                string user = txtOrder.Text;
                BindMyData(0);
            }
            else
            {
                alert = "<script>alert('请先选择客户');</script>";
            }
        }
        protected void Button_NoCall_Command(object sender, CommandEventArgs e)
        {
            if (TextBox1.Value != "")
            {
                string IDList = TextBox1.Value.TrimEnd(new char[] { ',' });
                string[] CustomerId = IDList.Split(',');
                foreach (string id in CustomerId)
                {
                    var myEditQuery = (from a in db.TCrm_KF_Customer where a.CustomerID == id select a).Single();
                    myEditQuery.NoCall = true; ;
                    db.SubmitChanges();
                }
                string user = txtOrder.Text;
                BindMyData(0);
            }
            else
            {
                alert = "<script>alert('请先选择客户');</script>";
            }
        }
    }
}
